import React from 'react'
import { Toast } from 'antd-mobile'
import './index.scss'
import axios from 'axios'
import { getCity } from '../../utils/getCity'
import { List, AutoSizer } from 'react-virtualized'
import NavHeader from '../../components/NavHeader'

export default class CityList extends React.Component {
  CITY = ['北京', '上海', '广州', '深圳']

  state = {
    cityList: {},
    cityIndex: [],
    activeIndex: 0
  }

  listComponent = React.createRef()

  async componentDidMount() {
    await this.getCityList()

    this.listComponent.current.measureAllRows()
  }

  processData = (data) => {
    const cityList = data.reduce((obj, item) => {
      let str = item.pinyin.substr(0, 1)

      if (obj[str]) {
        obj[str].push(item)
      } else {
        obj[str] = [item]
      }

      return obj
    }, {})

    const cityIndex = Object.keys(cityList).sort()

    return {
      cityIndex,
      cityList
    }
  }

  getCityList = async () => {
    const { data } = await axios.get('http://127.0.0.1:8080/area/city?level=1')

    if (data.status !== 200) {
      return alert(data.description)
    }

    const { cityIndex, cityList } = this.processData(data.body)

    const { data: hotData } = await axios.get('http://127.0.0.1:8080/area/hot')

    if (hotData.status !== 200) {
      return alert(hotData.description)
    }
    cityList['hot'] = hotData.body
    cityIndex.unshift('hot')

    const info = await getCity()
    cityList['#'] = [info]
    cityIndex.unshift('#')

    this.setState({
      cityIndex,
      cityList
    })
  }

  renderNavBar = () => {
    return (
      <NavHeader>城市列表</NavHeader>
    )
  }

  changeCity = (label, value) => {
    if(this.CITY.includes(label)) {
      localStorage.setItem('local_city', JSON.stringify({label, value}) )
      this.props.history.go(-1)
    } else {
      Toast.info('暂无当前城市房源信息', 1)
    }
  }

  rowRenderer = ({
    key, // 行数组中的唯一键
    index, // 行内集合的索引
    isScrolling, // 当前正在滚动列表
    isVisible, // 这一行在列表中可见（如它不是一个过多的行）
    style, // 要应用于行的样式对象（用于定位它）
  }) => {
    const { cityList, cityIndex } = this.state

    return (
      <div key={key} style={style} className="city-list-box">
        <div className="city-item-title">{cityIndex[index] === 'hot' ? '热门城市' : cityIndex[index].toUpperCase()}</div>
        { cityList[cityIndex[index]].map(item => {
          return (<div className="city-item-every" onClick={() => this.changeCity(item.label, item.value)} key={item.label}>{item.label}</div>)
        })}
      </div>
    )
  }

  rowHeight = ({ index }) => {
    const { cityIndex, cityList } = this.state

    return 36 + cityList[cityIndex[index]].length * 50
  }

  onRowsRendered = ({ startIndex }) => {
    if (startIndex !== this.state.activeIndex) {
      this.setState({
        activeIndex: startIndex
      })
    }
  }

  renderCityList = () => {
    return (
      <AutoSizer>
        {({ height, width }) => {
          return (
            <List
              ref={this.listComponent}
              width={width}
              height={height}
              rowCount={this.state.cityIndex.length}
              rowHeight={this.rowHeight}
              rowRenderer={this.rowRenderer}
              onRowsRendered={this.onRowsRendered}
              scrollToAlignment="start"
            />
          )
        }}
      </AutoSizer>
    )
  }

  renderCityIndex = () => {
    return (
      <div className="city-index">
        {this.state.cityIndex.map((item, index) => {
          return (<div key={item} className="city-index-item" onClick={() => {
            this.listComponent.current.scrollToRow(index)
          }}>
            <span className={this.state.activeIndex === index ? 'city-index-active' : ''}>{item === 'hot' ? '热' : item.toUpperCase()}</span>
          </div>)
        })}
      </div>
    )
  }

  render() {
    return (
      <div className="citylist">
        {this.renderNavBar()}

        {this.renderCityList()}

        {this.renderCityIndex()}
      </div>
    )
  }
}
